import axios from 'axios';// 引入axios
import serve from "../../static/indexConfig.js"
import loadEvents from '../commonFunction/loading.js'
import { Message } from 'element-ui';
var load = new loadEvents()
// 创建axios实例
var instance = axios.create({timeout: 1000 * 30});
// 设置根路径
if(process.env.NODE_ENV == "test"){
  instance.defaults.baseURL = serve.test;
}else if(process.env.NODE_ENV == "production"){
  instance.defaults.baseURL = serve.prod;
}else{
  instance.defaults.baseURL = serve.dev;
}

// 设置post请求头
instance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
// 添加请求拦截器，在请求头中加token
instance.interceptors.request
.use(
    config => {
      // 在请求头中添加token
      if (localStorage.getItem('token')) {
        config.headers.token = localStorage.getItem('token');
      }
      // 请求图片验证码或者发送验证码时不使用loading
      let url = config.url
      if((url.indexOf("image") == -1) && (url.indexOf("loginByCode") == -1)){
        // 请求加载效果
        load.open()
      }
      

      return config;
    },
    error => {
      return Promise.reject(error);
    }
);

instance.interceptors.response
.use(
  response=>{
    load.close()
    // if(!response.data.success){
    //   Message({center: true,message: response.data.message?response.data.message:"网络错误,请稍后再试",type: 'warning'});
    // }

    return response
  },
  error => {
    load.close()
    // Message({center: true,message:"网络错误,请稍后再试",type: 'warning'});
    return Promise.reject(error);
  }
)

export default instance;
